<template>
  <div class="s1">
    <el-main v-loading="loading" direction="vertical">
      <h2>DepartmentManual / 部门手册 整理</h2>
      <el-row>
        <el-col :span="24">
          1. DepartmentManual.db3 文件：
          <input
            ref="mInput1"
            type="file"
            accept=".db3"
            @change="db3FileChange"
          />
          <p v-if="depManulDb3OK === 2" class="ok el-icon-success"></p>
          <p v-if="depManulDb3OK === 0" class="not-ok el-icon-error"></p>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          2.所有 .pdf 部门手册文件：
          <input
            ref="mInput2"
            type="file"
            accept=".pdf"
            multiple
            @change="outputFolderChange"
          />
          <p v-if="pdfFilesOK" class="ok el-icon-success"></p>
          <p v-if="!pdfFilesOK" class="not-ok el-icon-error"></p>
        </el-col>
      </el-row>
      <el-col :span="24">
        <el-button
          class="el-icon-video-play"
          :disabled="!(pdfFilesOK && 2 === depManulDb3OK)"
          type="primary"
          plain
          @click="outputFiles"
          >开始整理</el-button
        >
      </el-col>
    </el-main>
  </div>
</template>

<script>
// const fs = require("fs-extra");
// const { shell } = require("electron");
import fs from "fs-extra";
// import sqlite3 from "sqlite3";
const sqlite3 = require("sqlite3");
import { open } from "sqlite";
import { shell } from "electron";
var db;
String.prototype.replaceAll = function(FindText, RepText) {
  const regExp = new RegExp(FindText, "g");
  return this.replace(regExp, RepText);
};
function getFolder(fileObj, task) {
  var _path = fileObj.path.replaceAll(fileObj.name, "");
  if (undefined === task.folderName) {
    _path += "Other/";
  } else {
    _path += task.folderName + "/";
  }
  return _path;
}
export default {
  name: "mainManual",
  data: function() {
    return {
      manualPlusDb3Path: undefined,
      pdfFiles: undefined,
      pdfFilesOK: false,
      taskList: [],
      deptmanual2dept: [],
      deptmanual2fleet: [],
      message_type: [],
      depManulDb3OK: 0,
      loading: false,
    };
  },
  watch: {
    manualPlusDb3Path: function(newVal) {
      console.log("manualPlusDb3Path wacted:", newVal);
    },
    taskList: function(newVal) {
      console.log("taskList wacted length:", newVal.length);
      if (newVal.length > 100) {
        this.depManulDb3OK = 2;
        // this.$notify({
        // 	title: "成功",
        // 	message: "数据库读取完成",
        // 	type: "success"
        // });
      } else {
        this.depManulDb3OK = 0;
      }
    },
    deptmanual2dept: function(newVal) {
      console.log("deptmanual2dept wacted length:", newVal.length);
      if (newVal.length > 10) {
        this.depManulDb3OK = 2;
        // this.$notify({
        // 	title: "成功",
        // 	message: "数据库读取完成",
        // 	type: "success"
        // });
      } else {
        this.depManulDb3OK = 0;
      }
    },
    message_type: function(newVal) {
      console.log("message_type wacted length:", newVal.length);
      if (newVal.length > 10) {
        this.depManulDb3OK = 2;
        this.$notify({
          title: "成功",
          message: "数据库读取完成",
          type: "success",
        });
      } else {
        this.depManulDb3OK = 0;
      }
    },
    pdfFiles: function(newVal) {
      if (newVal.length > 5) {
        this.pdfFilesOK = true;
        this.$notify({
          title: "成功",
          message: "手册文件选择成功",
          type: "success",
        });
      } else {
        this.pdfFilesOK = false;
      }
    },
  },
  methods: {
    db3FileChange: function(event) {
      var e = event;
      try {
        console.log(e.target);
        this.manualPlusDb3Path = e.target.files[0].path;
        this.taskManualPlusDb3(this.manualPlusDb3Path);
      } catch (error) {
        console.warn(error);
      }
    },
    outputFolderChange: function(e) {
      console.log(e.target);
      this.pdfFiles = e.target.files;
    },
    taskManualPlusDb3: async function(path) {
      const that = this;
      that.taskList = [];
      that.deptmanual2dept = [];
      that.message_type = [];
      if (undefined !== path) {
        db = new sqlite3.Database(
          path,
          sqlite3,
          sqlite3.OPEN_READONLY,
          (err) => {
            console.log("db db = new sqlite3.Database err =", err);
          }
        );
        // db = await open({
        // 	filename: path,
        // 	driver: sqlite3.Database
        // });
        // db = db.db;
        console.log("taskManualPlusDb3-----------", db);
        // deptmanual_list ID 就是 deptmanual2dept.MANUALLIST_ID 所以替换为 deptmanual2dept.MESSAGETYPEID
        // 再根据 message_type.MESSAGETYPEID 替换为 message_type.S_NAME
        await db.each("SELECT * FROM deptmanual_list", (err, row) => {
          try {
            if (
              undefined !== row.MD5 && //MD5 文件原有的名称，但是不带.pdf
              undefined !== row.ID && //ID 文件所在的文件夹
              undefined !== row.FILE_NAME //FILE_NAME 文件后来的名称，但是不带.pdf
            ) {
              row.MD5 += ".pdf";
              that.depManulDb3OK = 1;
              that.taskList.push(row);
            }
          } catch (err) {
            console.warn("所选择的DB3文件不对", err);
            that.depManulDb3OK = 0;
          }
        });
        await db.each("SELECT * FROM deptmanual2fleet", (err, row) => {
          try {
            if (
              undefined !== row.MANUAL2FLEET_ID &&
              undefined !== row.MANUALLIST_ID &&
              undefined !== row.MESSAGETYPEID
            ) {
              that.depManulDb3OK = 1;
              that.deptmanual2fleet.push(row);
            }
          } catch (err) {
            console.warn("所选择的DB3文件不对", err);
            that.depManulDb3OK = 0;
          }
        });
        await db.each("SELECT * FROM deptmanual2dept", (err, row) => {
          try {
            if (
              undefined !== row.MANUAL2DEPT_ID &&
              undefined !== row.MANUALLIST_ID &&
              undefined !== row.MESSAGETYPEID
            ) {
              that.depManulDb3OK = 1;
              that.deptmanual2dept.push(row);
            }
          } catch (err) {
            console.warn("所选择的DB3文件不对", err);
            that.depManulDb3OK = 0;
          }
        });
        await db.each("SELECT * FROM message_type", (err, row) => {
          try {
            if (undefined !== row.MESSAGETYPEID && undefined !== row.S_NAME) {
              that.depManulDb3OK = 1;
              that.message_type.push(row);
            }
          } catch (err) {
            console.warn("所选择的DB3文件不对", err);
            that.depManulDb3OK = 0;
          }
        });
        await db.close();
      }
    },
    configTaskList: async function() {
      const that = this;
      var i = 0;
      // (taskList)deptmanual_list ID 就是 deptmanual2dept.MANUALLIST_ID 所以替换为 deptmanual2dept.MESSAGETYPEID
      // 再根据 message_type.MESSAGETYPEID 替换为 message_type.S_NAME
      this.taskList = this.taskList.map((element) => {
        var _temp = element;
        for (i = 0; i < that.deptmanual2fleet.length; i++) {
          if (
            that.deptmanual2fleet[i].MANUALLIST_ID.trim() === _temp.ID.trim()
          ) {
            _temp.folderName1 = that.deptmanual2fleet[i].MESSAGETYPEID.trim();
            break;
          }
        }
        for (i = 0; i < that.deptmanual2dept.length; i++) {
          if (
            that.deptmanual2dept[i].MANUALLIST_ID.trim() === _temp.ID.trim()
          ) {
            _temp.folderName2 = that.deptmanual2dept[i].MESSAGETYPEID.trim();
            break;
          }
        }
        for (i = 0; i < that.message_type.length; i++) {
          _temp.folderName = "";
          if (that.message_type[i].MESSAGETYPEID.trim() === _temp.folderName1) {
            _temp.folderName = that.message_type[i].S_NAME + "/";
            break;
          }
          if (that.message_type[i].MESSAGETYPEID.trim() === _temp.folderName2) {
            _temp.folderName += that.message_type[i].S_NAME;
            break;
          }
        }
        return _temp;
      });
      console.log(this.taskList);
    },
    outputFiles: async function() {
      await this.configTaskList();
      var i = 0;
      var j = 0;
      this.loading = true;
      var shellDir = "";
      function _go(file, task) {
        var _targetAddress = getFolder(file, task);
        shellDir = file.path.replaceAll(file.name, "");
        fs.ensureDirSync(_targetAddress);
        if ("" === task.FILE_NAME || undefined === task.FILE_NAME) {
          task.FILE_NAME = file.name;
        }
        _targetAddress += task.FILE_NAME;
        fs.moveSync(file.path, _targetAddress, {
          overwrite: true,
        });
      }
      for (i = 0; i < this.pdfFiles.length; i++) {
        for (j = 0; j < this.taskList.length; j++) {
          if (
            this.pdfFiles[i].name.toUpperCase() ===
            this.taskList[j].MD5.toUpperCase() //this.taskList[j].MD5已经进行了 += ".pdf"
          ) {
            _go(this.pdfFiles[i], this.taskList[j]);
            break;
          }
        }
      }
      this.pdfFilesOK = false;
      this.depManulDb3OK = 2;
      this.loading = false;
      this.$notify({
        title: "成功",
        message: "文件整理完成",
        type: "success",
      });
    },
  },
  mounted: function() {},
};
</script>
<style>
.s1 .el-row {
  margin-top: 3%;
}

.s1 .ok {
  color: #67c23a;
}
.s1 .not-ok {
  color: #f56c6c;
}
</style>
